package com.helmlabs.grouper.forms.processor;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.helmlabs.grouper.forms.model.Form;
import com.helmlabs.grouper.forms.model.field.AbstractField;
import com.helmlabs.grouper.forms.model.field.MultiValueAbstractField;
import com.helmlabs.grouper.forms.model.field.NameValuePair;

public class HttpServletProcessor {
	
	private Log log = LogFactory.getLog(getClass());
	private HttpServletRequest request;
	private HttpServletResponse response;
	
	public Form process(Form form){
		log.debug("beginning processing the form posted through HttpServlet");
		
		// Fill the values of all the fields
		for (AbstractField field : form.getFields()){
			
			// If this is a multi value field, we need to handle it
			// differently 
			if (field instanceof MultiValueAbstractField){
				log.debug("This is a multi value field");
				String[] answers = request.getParameterValues(field.getName());
				List a = new ArrayList();
				
				// Add all the answers to the list and set the value
				for (int i=0; i<answers.length; i++){
					log.debug("adding the result " + answers[i] + " to the list");
					
					// if the given answer is an option, then add that option to the
					// list of values for this field
					for (Iterator<NameValuePair> options = ((MultiValueAbstractField)field).getOptions().iterator(); options.hasNext();){
						NameValuePair pair = options.next();
						if (pair.equals(answers[i])){
							a.add(pair);
							break;
						}
					}
				}
				
				((List)((MultiValueAbstractField)field).getValue()).addAll(a);
			} 
			// if this is not a multi value field, then we can
			// handle it normally
			else {
				if (field.getName()!=null){
					String answer = request.getParameter(field.getName());
					if (answer!=null && !"".equals(answer)){
						field.setValue(answer);
					}
				}
			}
		}
		return form;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}
	
	

}
